package com.glSto.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.glSto.config.SsoOAuthProperties;
import com.glSto.service.AuthenticationService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("api/Power.GULEISTO/GULEISTO")
public class AuthenticationController {

    private static final Logger authenticationLogger = LoggerFactory.getLogger("com.glSto.controller.AuthenticationController.oAuth");

    @Value("${user.url}")
    private String CREATE_USER_URL;
    @Value("${org.url}")
    private String CREATE_ORG_URL;

    @Autowired
    private SsoOAuthProperties ssoOAuthProperties;

    @Resource
    private AuthenticationService authenticationService;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 产生单点登录连接
     */
    @GetMapping("AuthLogin")
    public Map<String, Object> oAuthLogin(String userCode, String redirectUrl) {
        authenticationLogger.info("开始处理OAuth登录请求, userCode: {}, redirectUrl: {}", userCode, redirectUrl);
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);

        // 检查用户是否存在
        authenticationLogger.info("准备调用 authenticationService.checkUserExists");
        boolean userExists = authenticationService.checkUserExists(userCode);
        authenticationLogger.info("checkUserExists 结果: {}", userExists);
        if (!userExists) {
            result.put("success", false);
            result.put("data", "未找到用户或用户账号未启用");
            return result;
        }

        // 获取统一认证配置（优先使用数据库配置，否则使用配置文件默认值）
        authenticationLogger.info("准备获取认证配置");
        Map<String, String> authConfig = authenticationService.getAuthConfig();
        authenticationLogger.info("获取到的认证配置: {}", authConfig);
        String formatUrl = authConfig.getOrDefault("Configvalue", ssoOAuthProperties.getDefaultUrl());

        // 处理跳转URL
        if (redirectUrl == null || redirectUrl.isEmpty()) {
            redirectUrl = formatUrl + "WebCenter/Open?bizAreaId=00000000-0000-0000-0000-00000000000a";
        } else {
            redirectUrl = formatUrl + redirectUrl;
        }

        // 获取OAuth配置（优先使用数据库配置，否则使用配置文件）
        authenticationLogger.info("准备获取OAuth配置");
        Map<String, String> oauthConfig = authenticationService.getOAuthConfig();
        authenticationLogger.info("获取到的OAuth配置: {}", oauthConfig);
        String clientId = oauthConfig.getOrDefault("Id", ssoOAuthProperties.getClientId());
        String secret = oauthConfig.getOrDefault("secret", ssoOAuthProperties.getSecret());

        // 生成时间戳和签名
        long timestamp = System.currentTimeMillis();
        String signature = generateHmacSHA1(secret, clientId + userCode + timestamp);

        // Base64编码跳转URL
        String encodedRedirectUrl = Base64.getEncoder().encodeToString(redirectUrl.getBytes(StandardCharsets.UTF_8));

        // 拼接单点登录URL
        String loginUrl = String.format(
                "%sAccount/GetOAuth?clientid=%s&usercode=%s&state=%s&key=%s&redirect_uri=%s&epsprojid=",
                formatUrl, clientId, userCode, timestamp, signature, encodedRedirectUrl
        );

        result.put("data", loginUrl);
        authenticationLogger.info("单点登录连接：{}", loginUrl);

        return result;
    }


    /**
     * 统一身份认证消息订阅人员信息接收 - 创建-删除
     */
    @GetMapping("TYSF_XXDY_RY")
    public String handleUserEvent(
            String EventType, String account_uid, String ry_uid, String cn, String appFullName,
            String sp_employeehrnumber, String sp_gender, String employeenumber, String corpemployeeNumber,
            String ou, String sp_orgnumber, String departmentnumber, String sp_orgnamepath,
            String sp_orgcodepath, String mail, String sp_employeelevel, String sp_entrystatus,
            String sp_nation, String c, String sp_updatedate, String sp_employeesubtype,
            String sp_positionstatus, String employeetype, String usertype, String sp_country,
            String telephonenumber, String sp_positionname, String sp_positionnumber,
            String sp_titlelevel, String sp_pluralitytitles, String sp_titlenumber,
            String sp_titlecategory, String workmail) {

        // 解码所有参数
        EventType = decodeUrlParam(EventType);
        account_uid = decodeUrlParam(account_uid);
        ry_uid = decodeUrlParam(ry_uid);
        cn = decodeUrlParam(cn);
        appFullName = decodeUrlParam(appFullName);
        sp_employeehrnumber = decodeUrlParam(sp_employeehrnumber);
        sp_gender = decodeUrlParam(sp_gender);
        employeenumber = decodeUrlParam(employeenumber);
        corpemployeeNumber = decodeUrlParam(corpemployeeNumber);
        ou = decodeUrlParam(ou);
        sp_orgnumber = decodeUrlParam(sp_orgnumber);
        departmentnumber = decodeUrlParam(departmentnumber);
        sp_orgnamepath = decodeUrlParam(sp_orgnamepath);
        sp_orgcodepath = decodeUrlParam(sp_orgcodepath);
        mail = decodeUrlParam(mail);
        sp_employeelevel = decodeUrlParam(sp_employeelevel);
        sp_entrystatus = decodeUrlParam(sp_entrystatus);
        sp_nation = decodeUrlParam(sp_nation);
        c = decodeUrlParam(c);
        sp_updatedate = decodeUrlParam(sp_updatedate);
        sp_employeesubtype = decodeUrlParam(sp_employeesubtype);
        sp_positionstatus = decodeUrlParam(sp_positionstatus);
        employeetype = decodeUrlParam(employeetype);
        usertype = decodeUrlParam(usertype);
        sp_country = decodeUrlParam(sp_country);
        telephonenumber = decodeUrlParam(telephonenumber);
        sp_positionname = decodeUrlParam(sp_positionname);
        sp_positionnumber = decodeUrlParam(sp_positionnumber);
        sp_titlelevel = decodeUrlParam(sp_titlelevel);
        sp_pluralitytitles = decodeUrlParam(sp_pluralitytitles);
        sp_titlenumber = decodeUrlParam(sp_titlenumber);
        sp_titlecategory = decodeUrlParam(sp_titlecategory);
        workmail = decodeUrlParam(workmail);

        String result;
        try {
            switch (EventType) {
                case "ACCOUNT_CREATED":
                    Map<String, Object> createParams = buildUserParams(
                            account_uid, ry_uid, cn, appFullName,
                            sp_employeehrnumber, sp_gender, employeenumber, corpemployeeNumber,
                            ou, sp_orgnumber, departmentnumber, sp_orgnamepath, sp_orgcodepath,
                            mail, sp_employeelevel, sp_entrystatus, sp_nation, c,
                            sp_updatedate, sp_employeesubtype, sp_positionstatus, employeetype,
                            usertype, sp_country, telephonenumber, sp_positionname, sp_positionnumber,
                            sp_titlelevel, sp_pluralitytitles, sp_titlenumber, sp_titlecategory, workmail,"CREATE"
                    );
                    result = callCreateUserApi(createParams);
                    break;
                case "ACCOUNT_UPDATED":
                    Map<String, Object> updateParams = buildUserParams(
                            account_uid, ry_uid, cn, appFullName,
                            sp_employeehrnumber, sp_gender, employeenumber, corpemployeeNumber,
                            ou, sp_orgnumber, departmentnumber, sp_orgnamepath, sp_orgcodepath,
                            mail, sp_employeelevel, sp_entrystatus, sp_nation, c,
                            sp_updatedate, sp_employeesubtype, sp_positionstatus, employeetype,
                            usertype, sp_country, telephonenumber, sp_positionname, sp_positionnumber,
                            sp_titlelevel, sp_pluralitytitles, sp_titlenumber, sp_titlecategory, workmail,"UPDATE"
                    );
                    result = callCreateUserApi(updateParams);
                    break;
                default:
                    result = "不支持的事件类型: " + EventType;
            }
        } catch (Exception e) {
            result = "处理失败: " + e.getMessage();
        }
        log.info("处理结果: " + result);
        return result;

    }


    private Map<String, Object> buildUserParams(
            String accountUid, String ryUid, String userName, String appFullName,
            String employeeHrNumber, String gender, String employeeNumber, String corpEmployeeNumber,
            String ou, String orgNumber, String departmentNumber, String orgNamePath, String orgCodePath,
            String email, String employeeLevel, String entryStatus, String nation, String countryCode,
            String updateDate, String employeeSubtype, String positionStatus, String employeeType,
            String userType, String country, String phone, String positionName, String positionNumber,
            String titleLevel, String pluralityTitles, String titleNumber, String titleCategory, String workMail, String operationType
    ){
        Map<String, Object> params = new HashMap<>();

        // 基础参数
        params.put("dataType", "STO_SYS_02");
//        params.put("appKey", appKey);
        params.put("appKey", "stoApply");
        params.put("timestamp", "1750644948350");
//        params.put("accessToken", accessToken);
        params.put("accessToken", "5411706e6b4a662481bcbeed9f4aec60");
        params.put("operationType", operationType);

        // 业务数据
        Map<String, Object> data = new HashMap<>();
        data.put("userAccount", accountUid);
        data.put("userName", userName);
        data.put("humCode", employeeHrNumber);
        data.put("sex", gender);
        data.put("email", email);
        data.put("nation", nation);
        data.put("userType", userType);
        data.put("country", country);
        data.put("mobile", phone);
        data.put("posiName", positionName);
        data.put("sourceUserId", accountUid);
        data.put("sourceMajorOrgId", departmentNumber);
        data.put("sourceParentOrgId", departmentNumber);
        data.put("orderNum", null);
        data.put("statusCode", "启用");

        Map<String, Object> sourceApiData = new HashMap<>();
        sourceApiData.put("accountUid", accountUid);
        sourceApiData.put("ryUid", ryUid);
        sourceApiData.put("userName", userName);
        sourceApiData.put("appFullName", appFullName);
        sourceApiData.put("employeeHrNumber", employeeHrNumber);
        sourceApiData.put("gender", gender);
        sourceApiData.put("employeeNumber", employeeNumber);
        sourceApiData.put("corpEmployeeNumber", corpEmployeeNumber);
        sourceApiData.put("ou", ou);
        sourceApiData.put("orgNumber", orgNumber);
        sourceApiData.put("departmentNumber", departmentNumber);
        sourceApiData.put("orgNamePath", orgNamePath);
        sourceApiData.put("orgCodePath", orgCodePath);
        sourceApiData.put("email", email);
        sourceApiData.put("employeeLevel", employeeLevel);
        sourceApiData.put("entryStatus", entryStatus);
        sourceApiData.put("nation", nation);
        sourceApiData.put("countryCode", countryCode);
        sourceApiData.put("updateDate", updateDate);
        sourceApiData.put("employeeSubtype", employeeSubtype);
        sourceApiData.put("positionStatus", positionStatus);
        sourceApiData.put("employeeType", employeeType);
        sourceApiData.put("userType", userType);
        sourceApiData.put("country", country);
        sourceApiData.put("phone", phone);
        sourceApiData.put("positionName", positionName);
        sourceApiData.put("positionNumber", positionNumber);
        sourceApiData.put("titleLevel", titleLevel);
        sourceApiData.put("pluralityTitles", pluralityTitles);
        sourceApiData.put("titleNumber", titleNumber);
        sourceApiData.put("titleCategory", titleCategory);
        sourceApiData.put("workMail", workMail);

        data.put("sourceApiData", sourceApiData);
        params.put("data", data);
        return params;
    }

    /**
     * 调用创建用户的外部接口
     */
    private String callCreateUserApi(Map<String, Object> params) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonBody = objectMapper.writeValueAsString(params);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> request = new HttpEntity<>(jsonBody, headers);

        authenticationLogger.info("创建用户请求参数：{}", jsonBody);
        String response = restTemplate.postForObject(CREATE_USER_URL, request, String.class);

        // 解析响应结果
        if (response != null && (response.contains("\"success\":true") || response.contains("\"code\":200"))) {
            authenticationLogger.info("处理结果：{}", response);
            return response;
        }else {
            authenticationLogger.error("处理结果：{}", response);
            return response;
        }
    }


    /**
     * 统一身份认证消息订阅人员信息接收 - 禁用-启用-删除
     */
    @GetMapping("TYSF_XXDY_RYJY")
    public String handleUserStatusChange(String EventType, String account_uid, String ry_uid) {
        ry_uid = decodeUrlParam(ry_uid);
        account_uid = decodeUrlParam(account_uid);

        String result;
        try {
            Map<String, Object> params = buildUserStatusParams(account_uid, EventType);
            result = callCreateUserApi(params); // 复用创建用户的接口
        } catch (Exception e) {
            result = "处理失败: " + e.getMessage();
        }
        authenticationLogger.info("处理结果：{}", result);
        return result;
    }

    private Map<String, Object> buildUserStatusParams(String accountUid, String eventType) {
        Map<String, Object> params = new HashMap<>();

        // 基础参数
        params.put("dataType", "STO_SYS_02");
        params.put("appKey", "stoApply");
        params.put("timestamp", "1750644948350");
        params.put("accessToken", "5411706e6b4a662481bcbeed9f4aec60");

        // 操作类型映射
        String operationType;
        String statusCode;

        switch (eventType) {
            case "ACCOUNT_DISABLED":
                operationType = "FREEZE";
                statusCode = "禁用";
                break;
            case "ACCOUNT_ENABLED":
                operationType = "START";
                statusCode = "启用";
                break;
            case "ACCOUNT_DELETED":
                operationType = "DELETE";
                statusCode = "删除";
                break;
            default:
                throw new IllegalArgumentException("不支持的事件类型: " + eventType);
        }

        params.put("operationType", operationType);


        Map<String, Object> data = new HashMap<>();
        data.put("userAccount", accountUid);
        data.put("sourceUserId", accountUid);
        data.put("statusCode", statusCode);
        params.put("data", data);

        return params;
    }


    /**
     * 统一身份认证消息订阅组织信息接收
     */
    @GetMapping("TYSF_XXDY_ZZ")
    public String handleOrganizationEvent(
            String EventType, String OU, String CN, String SPFULLNAME, String SPOUTYPE,
            String SPORGLEVEL, String SPORGNAMEPATH, String SPORGCODEPATH,
            String SPSUPERVISORYDEPARTMENT, String SPENTRYSTATUS, String BUSINESSCATEGORY,
            String POSTALCODE, String SPORGLEVELNUMBER, String POSTALADDRESS,
            String SPISLEAF, String SPPARENTS, String SPPUBLICCOMPANY,
            String SPORGNUMBER, String SPMANAGERNUMBER, String SPORDER,
            String SPREPORTINGDEPARTMENT) {

        // 解码所有参数
        OU = decodeUrlParam(OU);
        CN = decodeUrlParam(CN);
        SPFULLNAME = decodeUrlParam(SPFULLNAME);
        SPOUTYPE = decodeUrlParam(SPOUTYPE);
        SPORGLEVEL = decodeUrlParam(SPORGLEVEL);
        SPORGNAMEPATH = decodeUrlParam(SPORGNAMEPATH);
        SPORGCODEPATH = decodeUrlParam(SPORGCODEPATH);
        SPSUPERVISORYDEPARTMENT = decodeUrlParam(SPSUPERVISORYDEPARTMENT);
        SPENTRYSTATUS = decodeUrlParam(SPENTRYSTATUS);
        BUSINESSCATEGORY = decodeUrlParam(BUSINESSCATEGORY);
        POSTALCODE = decodeUrlParam(POSTALCODE);
        SPORGLEVELNUMBER = decodeUrlParam(SPORGLEVELNUMBER);
        POSTALADDRESS = decodeUrlParam(POSTALADDRESS);
        SPISLEAF = decodeUrlParam(SPISLEAF);
        SPPARENTS = decodeUrlParam(SPPARENTS);
        SPPUBLICCOMPANY = decodeUrlParam(SPPUBLICCOMPANY);
        SPORGNUMBER = decodeUrlParam(SPORGNUMBER);
        SPMANAGERNUMBER = decodeUrlParam(SPMANAGERNUMBER);
        SPORDER = decodeUrlParam(SPORDER);
        SPREPORTINGDEPARTMENT = decodeUrlParam(SPREPORTINGDEPARTMENT);

        String result;
        try {
            switch (EventType) {
                case "ORGUNIT_CREATED":
                    result = createOrganization(OU, CN, SPFULLNAME, SPOUTYPE, SPORGLEVEL,
                            SPORGNAMEPATH, SPORGCODEPATH, SPSUPERVISORYDEPARTMENT,
                            SPENTRYSTATUS, BUSINESSCATEGORY, POSTALCODE,
                            SPORGLEVELNUMBER, POSTALADDRESS, SPISLEAF,
                            SPPARENTS, SPPUBLICCOMPANY, SPORGNUMBER,
                            SPMANAGERNUMBER, SPORDER, SPREPORTINGDEPARTMENT);
                    break;
                case "ORGUNIT_MODIFIED":
                    result = updateOrganization(OU, CN, SPFULLNAME, SPOUTYPE, SPORGLEVEL,
                            SPORGNAMEPATH, SPORGCODEPATH, SPSUPERVISORYDEPARTMENT,
                            SPENTRYSTATUS, BUSINESSCATEGORY, POSTALCODE,
                            SPORGLEVELNUMBER, POSTALADDRESS, SPISLEAF,
                            SPPARENTS, SPPUBLICCOMPANY, SPORGNUMBER,
                            SPMANAGERNUMBER, SPORDER, SPREPORTINGDEPARTMENT);
                    break;
                default:
                    result = "不支持的事件类型: " + EventType;
            }
        } catch (Exception e) {
            result = "处理失败: " + e.getMessage();
        }

        // 记录日志
//        authenticationService.logOrgEvent(EventType, result, "TYSF_XXDY_ZZ");

        authenticationLogger.info("处理结果：{}", result);
        return result;
    }

    private String createOrganization(String OU, String CN, String SPFULLNAME, String SPOUTYPE, String SPORGLEVEL,
                                      String SPORGNAMEPATH, String SPORGCODEPATH, String SPSUPERVISORYDEPARTMENT,
                                      String SPENTRYSTATUS, String BUSINESSCATEGORY, String POSTALCODE,
                                      String SPORGLEVELNUMBER, String POSTALADDRESS, String SPISLEAF,
                                      String SPPARENTS, String SPPUBLICCOMPANY, String SPORGNUMBER,
                                      String SPMANAGERNUMBER, String SPORDER, String SPREPORTINGDEPARTMENT) throws JsonProcessingException {
        return callExternalOrgApi(OU, CN, SPFULLNAME, SPOUTYPE, SPORGLEVEL,
                SPORGNAMEPATH, SPORGCODEPATH, SPSUPERVISORYDEPARTMENT,
                SPENTRYSTATUS, BUSINESSCATEGORY, POSTALCODE,
                SPORGLEVELNUMBER, POSTALADDRESS, SPISLEAF,
                SPPARENTS, SPPUBLICCOMPANY, SPORGNUMBER,
                SPMANAGERNUMBER, SPORDER, SPREPORTINGDEPARTMENT, "CREATE");
    }

    private String updateOrganization(String OU, String CN, String SPFULLNAME, String SPOUTYPE, String SPORGLEVEL,
                                      String SPORGNAMEPATH, String SPORGCODEPATH, String SPSUPERVISORYDEPARTMENT,
                                      String SPENTRYSTATUS, String BUSINESSCATEGORY, String POSTALCODE,
                                      String SPORGLEVELNUMBER, String POSTALADDRESS, String SPISLEAF,
                                      String SPPARENTS, String SPPUBLICCOMPANY, String SPORGNUMBER,
                                      String SPMANAGERNUMBER, String SPORDER, String SPREPORTINGDEPARTMENT) throws JsonProcessingException {
        return callExternalOrgApi(OU, CN, SPFULLNAME, SPOUTYPE, SPORGLEVEL,
                SPORGNAMEPATH, SPORGCODEPATH, SPSUPERVISORYDEPARTMENT,
                SPENTRYSTATUS, BUSINESSCATEGORY, POSTALCODE,
                SPORGLEVELNUMBER, POSTALADDRESS, SPISLEAF,
                SPPARENTS, SPPUBLICCOMPANY, SPORGNUMBER,
                SPMANAGERNUMBER, SPORDER, SPREPORTINGDEPARTMENT, "UPDATE");
    }

    private String callExternalOrgApi(String OU, String CN, String SPFULLNAME, String SPOUTYPE, String SPORGLEVEL,
                                      String SPORGNAMEPATH, String SPORGCODEPATH, String SPSUPERVISORYDEPARTMENT,
                                      String SPENTRYSTATUS, String BUSINESSCATEGORY, String POSTALCODE,
                                      String SPORGLEVELNUMBER, String POSTALADDRESS, String SPISLEAF,
                                      String SPPARENTS, String SPPUBLICCOMPANY, String SPORGNUMBER,
                                      String SPMANAGERNUMBER, String SPORDER, String SPREPORTINGDEPARTMENT,
                                      String operationType) throws JsonProcessingException {
        // 构建请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("dataType", "STO_SYS_01");
        requestBody.put("appKey", "stoApply");
        requestBody.put("timestamp", "1750644948350");
        requestBody.put("accessToken", "5411706e6b4a662481bcbeed9f4aec60");
        requestBody.put("operationType", operationType);

        Map<String, Object> data = new HashMap<>();


        data.put("orgCode", OU);
        data.put("orgName", CN);
        data.put("orgNameAbbr", SPFULLNAME);
        data.put("orgType", SPOUTYPE);

        data.put("sourceOrgId", OU);

        data.put("parentOrgCode", SPSUPERVISORYDEPARTMENT);
        Integer orderNum = 1;
        if (SPORDER != null && !SPORDER.trim().isEmpty()) {
            try {
                orderNum = Integer.parseInt(SPORDER.trim());
            } catch (NumberFormatException e) {
                authenticationLogger.error("SPORDER非数字：{}", SPORDER, e);
                throw new RuntimeException("排序号需为整数");
            }
        }
        data.put("orderNum", orderNum);
        data.put("statusCode", SPENTRYSTATUS);

        Map<String, Object> sourceApiData = new HashMap<>();
        sourceApiData.put("OU", OU);
        sourceApiData.put("CN", CN);
        sourceApiData.put("SPFULLNAME", SPFULLNAME);
        sourceApiData.put("SPOUTYPE", SPOUTYPE);
        sourceApiData.put("SPORGLEVEL", SPORGLEVEL);
        sourceApiData.put("SPORGNAMEPATH", SPORGNAMEPATH);
        sourceApiData.put("SPORGCODEPATH", SPORGCODEPATH);
        sourceApiData.put("SPSUPERVISORYDEPARTMENT", SPSUPERVISORYDEPARTMENT);
        sourceApiData.put("SPENTRYSTATUS", SPENTRYSTATUS);
        sourceApiData.put("BUSINESSCATEGORY", BUSINESSCATEGORY);
        sourceApiData.put("POSTALCODE", POSTALCODE);
        sourceApiData.put("SPORGLEVELNUMBER", SPORGLEVELNUMBER);
        sourceApiData.put("POSTALADDRESS", POSTALADDRESS);
        sourceApiData.put("SPISLEAF", SPISLEAF);
        sourceApiData.put("SPPARENTS", SPPARENTS);
        sourceApiData.put("SPPUBLICCOMPANY", SPPUBLICCOMPANY);
        sourceApiData.put("SPORGNUMBER", SPORGNUMBER);
        sourceApiData.put("SPMANAGERNUMBER", SPMANAGERNUMBER);
        sourceApiData.put("SPORDER", orderNum);
        sourceApiData.put("SPREPORTINGDEPARTMENT", SPREPORTINGDEPARTMENT);

        data.put("sourceApiData", sourceApiData);
        requestBody.put("data", data);

        ObjectMapper mapper = new ObjectMapper();
        String jsonBody = mapper.writeValueAsString(requestBody);

        authenticationLogger.info("组织接口请求体: " + jsonBody);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> requestEntity = new HttpEntity<>(jsonBody, headers);

        return restTemplate.postForObject(CREATE_ORG_URL, requestEntity, String.class);
    }

    private String processOrderNum(String spOrder) {
        if (spOrder == null || spOrder.trim().isEmpty()) {
            return "";
        }
        String trimmedSpOrder = spOrder.trim();
        try {
            Integer.parseInt(trimmedSpOrder);
            return trimmedSpOrder;
        } catch (NumberFormatException e) {
            authenticationLogger.error("类型错误"+e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 统一身份认证消息订阅组织信息接收 - 删除
     */
    @GetMapping("TYSF_XXDY_ZZSC")
    public String handleOrganizationDeletion(String EventType, String OU, String CN) {
        OU = decodeUrlParam(OU);
        CN = decodeUrlParam(CN);

        String result;
        try {
            if ("ORGUNIT_DELETED".equals(EventType)) {
                // 构建删除请求参数
                Map<String, Object> deleteParams = buildOrganizationDeleteParams(OU, CN);
                // 复用调用组织接口的方法
                result = callExternalOrgApi(deleteParams);
            } else {
                result = "不支持的事件类型: " + EventType;
            }
        } catch (Exception e) {
            result = "处理失败: " + e.getMessage();
        }

        authenticationLogger.info("处理结果: {}", result);
        return result;
    }

    private Map<String, Object> buildOrganizationDeleteParams(String ou, String cn) {
        Map<String, Object> params = new HashMap<>();

        // 基础参数
        params.put("dataType", "STO_SYS_01");
        params.put("appKey", "stoApply");
        params.put("timestamp", "1750644948350");
        params.put("accessToken", "5411706e6b4a662481bcbeed9f4aec60");
        params.put("operationType", "DELETE");

        // 业务数据
        Map<String, Object> data = new HashMap<>();
        data.put("orgCode", ou);
        data.put("orgName", cn);
        data.put("sourceOrgId", ou);
        params.put("data", data);

        // sourceApiData（可选，但建议保留用于审计）
        Map<String, Object> sourceApiData = new HashMap<>();
        sourceApiData.put("OU", ou);
        sourceApiData.put("CN", cn);
        data.put("sourceApiData", sourceApiData);

        return params;
    }

    private String callExternalOrgApi(Map<String, Object> params) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        String jsonBody = mapper.writeValueAsString(params);

        authenticationLogger.info("组织接口请求体: {}", jsonBody);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> requestEntity = new HttpEntity<>(jsonBody, headers);

        return restTemplate.postForObject(CREATE_ORG_URL, requestEntity, String.class);
    }

    /**
     * 演示接口
     */
//    @PostMapping("GetOne")
    public Map<String, Object> getOne(String json) {
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);

        if (json == null || json.isEmpty()) {
            throw new IllegalArgumentException("错误的入参");
        }

        // 这里需要根据实际的TOneParam类进行JSON解析
        // TOneParam param = JsonUtils.fromJson(json, TOneParam.class);
        // Object tmpResult = authenticationService.getOne(param);
        // result.put("data", tmpResult);

        return result;
    }

    // ===== 工具方法 =====

    /**
     * 生成HMACSHA1签名
     */
    private String generateHmacSHA1(String secret, String data) {
        try {
            Mac mac = Mac.getInstance("HmacSHA1");
            SecretKeySpec secretKey = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA1");
            mac.init(secretKey);
            byte[] hashBytes = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));

            StringBuilder hexString = new StringBuilder();
            for (byte b : hashBytes) {
                String hex = String.format("%02X", b);
                hexString.append(hex);
            }
            return hexString.toString().toLowerCase();
        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            throw new RuntimeException("生成HMACSHA1签名失败", e);
        }
    }

    /**
     * URL参数解码
     */
    private String decodeUrlParam(String param) {
        if (param == null) {
            return null;
        }
        try {
            return java.net.URLDecoder.decode(param, String.valueOf(StandardCharsets.UTF_8));
        } catch (Exception e) {
            return param;
        }
    }

    /**
     * 解析日期字符串
     */
    private Date parseDate(String dateStr) {
        if (dateStr == null || dateStr.isEmpty()) {
            return null;
        }
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return sdf.parse(dateStr);
        } catch (ParseException e) {
            throw new IllegalArgumentException("日期格式错误: " + dateStr, e);
        }
    }
}
